package com.witmore.neutron.ai.web.wechat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.witmore.neutron.ai.db.entity.ScorpionTradingUserDO;
import com.witmore.neutron.ai.db.mapper.ScorpionTradingUserMapper;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * Description: ScorpionBaseController
 * Author: 豆子高
 * Date: 2025/8/19 12:52
 */
@Slf4j
@Service
public class ScorpionBaseController {

    @Autowired
    private ScorpionTradingUserMapper scorpionTradingUserMapper;

    /**
     * 验证用户登录状态
     */
    public void validateUserLogin() {
        UserSession userSession = GlobalAccountSession.getUserInfo();
        if (userSession == null || userSession.getId() == null) {
            log.warn("用户未登录或会话无效");
            return;
        }
        ScorpionTradingUserDO scorpionTradingUserDO = scorpionTradingUserMapper.selectOne(new LambdaQueryWrapper<ScorpionTradingUserDO>().eq(ScorpionTradingUserDO::getPhone, userSession.getUserPhone()));
        if (scorpionTradingUserDO == null) {
            ScorpionTradingUserDO userDO = new ScorpionTradingUserDO();
            userDO.setUserName(userSession.getUserName());
            userDO.setPhone(userSession.getUserPhone());
            userDO.setCreateTime(LocalDateTime.now());
            userDO.setUpdateTime(LocalDateTime.now());
            GlobalAccountSession.setUserInfo(userSession);
            scorpionTradingUserMapper.insert(userDO);
            scorpionTradingUserDO = userDO;
        }
        // 根据userSession.getUserPhone() 到scorpion_trading_user获取用户id
        userSession.setScorpionUserId(scorpionTradingUserDO.getId().intValue());
        userSession.setScorpionUserOpenid(scorpionTradingUserDO.getOpenid());
        GlobalAccountSession.setUserInfo(userSession);
    }
}
